package com.example.webbasic.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.function.Consumer;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 第一个Servlet
 * @author ben
 * @date 2021-11-06 15:31:15 CST
 */
public class MyServlet1 extends HttpServlet {

	private static final long serialVersionUID = 211106L;
	
	private static Consumer<Object> cs = System.out::println;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        cs.accept("doGet: uri=" + req.getRequestURI() + ", rp=" + req.getRemotePort() + ", lp=" + req.getLocalPort()
        		+ ", sp=" + req.getServerPort());
        
        cs.accept("doGet: url=" + req.getRequestURL() + ", laddr=" + req.getLocalAddr() + ", raddr=" + req.getRemoteAddr());
        cs.accept("sessionId=" + req.getRequestedSessionId());
        this.doPost(req, resp);
    }

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        cs.accept("doPost: uri=" + req.getRequestURI());
        cs.accept("doPost: url=" + req.getRequestURL());
        
        String uri = req.getRequestURI();
        if (uri.startsWith("/my/")) {
        	// 交给 MyController处理
        	
        	// 1、失败的转发方式
//        	this.service(req, resp);
//        	return;
        	
        	// 2、还是失败
//        	cs.accept("uri starts with /my/...");
//        	cs.accept(req.getDispatcherType());
//        	RequestDispatcher rd = req.getRequestDispatcher("/");
//        	cs.accept("rd=" + rd);
//        	rd.forward(req, resp);
//        	return;
        	
        	// 3、还是失败
//        	resp.sendRedirect("/my/hello");
//        	return;
        	
        	
        }
        
        // 响应
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("utf-8");
        
        PrintWriter out = resp.getWriter();
        out.print("url: " + req.getRequestURL());
        out.print("\r\n服务器时间：" + new Date());
    }
	
}
